<!DOCTYPE html>
<html class="loading" lang="en" data-textdirection="ltr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
<meta name="author" content="PIXINVENT">
<title>自助售货管理后台</title>
<link rel="stylesheet" type="text/css" href="app-assets/css/vendors.css">
<link rel="stylesheet" type="text/css" href="app-assets/css/vertical-menu.css">
<link rel="stylesheet" type="text/css" href="app-assets/css/bootstrap-extended.css">
</head>
<body>
<div class="content-wrapper">
  <div class="content-header ">
    <div class="content-header-left mb-2 clearfix">
		
      <h3 class="content-header-title mb-0 pull-left">编辑商品信息</h3>
		<ol class="breadcrumb pull-right">
                <li><a href="商品列表.html">商品列表</a></li>
                        <li class="active">编辑商品信息</li>
                      
                    </ol>
    </div>
  </div>
  <div class="card">
    <div class="card-content">
      <div class="card-body">
        <div class="funcbtn clearfix">
          <div class="pull-left"><a class="btn btn-default" href="商品列表.html"> 返回</a></div>
        </div>
        <div class="form1 form3" >
				<ul class="row">
					<li class="col-sm-10 col-xs-12">
						<span>商品名称：</span>
						<input type="text" class="form-control" placeholder="请输入商品名称" id="productName"> 
					</li>
					<li class="col-sm-10 col-xs-12">
						<span>商品品牌：</span>
						<input type="text" class="form-control" placeholder="请输入商品品牌" id="brand">
					</li>
					<li class="col-sm-10 col-xs-12">
						<span>商品建议零售价：</span>
						<input type="text" class="form-control" id="price">
					</li>
					<li class="col-sm-10 col-xs-12">
						<span>商品采购价:</span>
						<input type="text" class="form-control" id="purchasePrice">
					</li>
					<li class="col-sm-10 col-xs-12">
						<span>商品图片：</span>
						<div class="clearfix">
							<div class="pull-left">
								<div class="upimgbox">
									<img id="hxImg" src="app-assets/images/avatar.jpg">
								</div>
								<a href="#" class="file">
									<input type="file" id="imageUrl">选择图片</a>
							</div>
							<div class="pull-left p-l-20">
								<p class="text-info">格式：jpg、png、jpeg<br>
													像素:宽400px*高400px<br>
													大小:小于100K</p>
							</div>
						</div>
					</li>
					<li class="col-sm-10 col-xs-12">
						<span>商品分类：</span>
						<select class="form-control" id="selectCategories">
							<option></option>
						</select>
					</li>
					<li class="col-sm-10 col-xs-12">
						<span>供应商：</span>
						<select class="form-control" id="selectSuppliers">
							<option></option>
						</select>
					</li>
					<li class="col-sm-10 col-xs-12">
						<span>商品说明：</span>
						<textarea class="form-control" id="description"></textarea>
					</li>
					
				<li class="col-sm-10 col-xs-12">
					<input type="button" class="btn btn-primary" value="确认保存" id="saveButton"/>
				</li>
	
			</ul>
		</div>
      
      </div>
    </div>
  </div>
</div>


<script src="app-assets/js/vendors.min.js" type="text/javascript"></script> 
<script src="app-assets/js/app-menu.js" type="text/javascript"></script> 
<script src="app-assets/js/app.js" type="text/javascript"></script> 
<script src="app-assets/js/echarts.min.js" type="text/javascript"></script> 

</body>
</html>
<script type="module">
	import { getsupplierList, getCategoryList,baseUrl } from './date/js/comm.js';
	let productId='';
	$(function(){
		initPage();
	}); 
	
	async function initPage() {
    try {
        // 先加载下拉框数据
        await getsupplierList();
        await getCategoryList();
        
        // 然后处理商品信息
        const productId = getId();
        console.log('商品id', productId);
        
        if(productId && productId !== '' && productId !== undefined) {
            setTimeout(() => getProductInfo(productId), 100);
        }
        
        // 绑定保存按钮事件
        $('#saveButton').on('click', saveProduct);
        
    } catch (error) {
        console.error('页面初始化失败:', error);
    }
}




	//获取id
	function getId(){
		let url = window.location.href;
		let index = url.lastIndexOf('=');
		let id = url.substring(index+1);
		return id;
	}
	//获取商品信息
	function getProductInfo(productId){
		$.ajax({
			url:baseUrl+'/products/info/'+productId,
			type:'get',
			dataType:'json',
			success:function(result){
				console.log('获取商品信息',result);
				if(result.status){
					$('#productName').val(result.data.productName);
					$('#brand').val(result.data.brand);
					$('#price').val(result.data.price);
					$('#purchasePrice').val(result.data.purchasePrice);
					$('#description').val(result.data.description);
					$('#selectCategories').val(result.data.categoryId);
					$('#selectSuppliers').val(result.data.supplierId);
					if(result.data.imageUrl){
						$('#hxImg').attr("src",baseUrl+result.data.imageUrl);
						$('#hxImg').css("opacity",100);
					}
				}
			}
		})
	}


	
	// 图片选中
    $('#imageUrl').on('change', function(event) {
        // event.target.files 获取到的是一个FileList对象，包含了用户选择的所有文件
        let files = event.target.files;
        if (files.length > 0) {
            // 只处理第一个被选中的文件
            let file = files[0];
            // 这里可以根据需要执行更多操作，比如预览图片、上传文件等
            let url = URL.createObjectURL(file)
            $('#hxImg').attr("src",url)
            $('#hxImg').css("opacity",100)
        }
    });

	//清空表单
	function clearForm(){
		$('#productName').val('');
		$('#brand').val('');
		$('#price').val('');
		$('#purchasePrice').val('');
		$('#hxImg').attr("src",'app-assets/images/avatar.jpg');
		$('#hxImg').css("opacity",0);
		$('#selectCategories').val('');
		$('#selectSuppliers').val('');
	}
	
	//保存数据
	function saveProduct(){ 
		//获取form数据
		let formData = new FormData();
		formData.append('productId',productId);
		formData.append('productName',$('#productName').val());
		formData.append('brand',$('#brand').val());
		formData.append('price',$('#price').val());
		formData.append('purchasePrice',$('#purchasePrice').val());
		formData.append('imageFile',$('#imageUrl')[0].files[0]);
		formData.append('categoryId',$('#selectCategories').val());
		formData.append('supplierId',$('#selectSuppliers').val());
		formData.append('description',$('#description').val());
		$.ajax({
			url:baseUrl+'/products/edit',
			type:'post',
			data:formData,
			processData:false,
			contentType:false,
			success:function(result){
				console.log('保存商品信息',result);
				if(result.status){
					alert('保存成功');
					clearForm();
					window.location.href = '商品列表.html';
				}
			}
		})
	}
	
</script>